<template>
<div class="search_suggestion">
<van-cell icon="search"
  v-for="(item,index) in suggestions" :key="index">
    <div slot="title" @click="$emit('search', item)"
    v-html="highlight (item)"></div>
</van-cell>
</div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: [],
      setTimeoutID: 0

    }
  },
  created () {
  },
  watch: {
    // 监听输入框发生变化
    searchText: {
      // 监听的数据发生变化就会触发这个钩子函数,钩子函数名字不能写错
      handler () {
        // console.log('发生了变化')
        // 防抖
        clearTimeout(this.setTimeoutID)
        this.setTimeoutID = setTimeout(() => {
          this.loadSuggestion()
        }, 600)
      },
      // 数据第一次输入时，就触发handler钩子函数
      immediate: true
    }
  },
  methods: {
    // 获取联想请求
    async loadSuggestion () {
      try {
        const { data: res } = await getSearchSuggestion(this.searchText)
        // console.log(res)
        this.suggestions = res.data.options
        // console.log(res)
      } catch (err) {
        this.$toast.fail('获取失败')
        // console.log(err)
      }
    },

    // 处理搜索建议高亮,
    highlight (text) {
      const replaceText = '<span style="color: red;">' + this.searchText + '</span>'
      // 正则
      const reg = new RegExp(this.searchText, 'gi')
      const newText = text.replace(reg, replaceText)
      return newText
    }
  }
}

</script>

<style scoped lang='less'>

</style>
